﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace E4RPTools
{
    public class ExceptionPublisher
    {
        private static string BuildExceptionInfo(Exception exception)
        {
            var textBuffer = new StringBuilder();
            textBuffer.AppendFormat(string.Format("DateTime: {0} {1}{2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), Environment.NewLine));
            textBuffer.AppendFormat(string.Format("Type: {0}{1}", exception.GetType().FullName, Environment.NewLine));
            textBuffer.AppendFormat(string.Format("Message: {0}{1}", exception.Message, Environment.NewLine));
            textBuffer.AppendFormat(string.Format("Source: {0}{1}", exception.Source, Environment.NewLine));
            if (exception.StackTrace != null)
                textBuffer.AppendFormat("{0}{1}", exception.StackTrace.Replace("\n", Environment.NewLine), Environment.NewLine);
            return textBuffer.ToString();
        }

        public static void Publish(string filePath, Exception exception)
        {
            using (var file = File.Open(filePath, FileMode.Append, FileAccess.Write))
            using (var writer = new StreamWriter(file))
                writer.Write(BuildExceptionInfo(exception));
        }

        public static void ShowErrorMessage(IWin32Window owner, string text, string caption)
        {
            MessageBox.Show(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }

        public static void PublishAndShowErrorMessage(IWin32Window owner, Exception e, string logFile, string product, string errorMessage)
        {
            Publish(logFile, e);
            ShowErrorMessage(owner, errorMessage, product);
        }
    }
}
